import {
  getImage,
  getPage,
  getTabbar,
  ChatConfig
} from '../../utils/config';
import api from '../../utils/api';
import {
  http,
  storage,
  promisify,
  $toast,
  $loading,
  $query
} from '../../utils/utils';
import wxApi from '../../utils/wxApi';
import {
  headerInfo
} from '../../utils/env'
const app = getApp();
let topStyle, leftStyle, tipTopStyle;

{
  let {
    height,
    right,
    menuWidth
  } = headerInfo
  console.log(headerInfo)
  leftStyle = `right: ${((menuWidth / 2) / 2) + right}px`;
  tipTopStyle = `top: ${height}px;`;
  topStyle = `top: ${height + 10}px;`;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    logged: 0,
    loading: 0,
    userId: 0,
    goodsNavFix: false,
    goodsNavType: 1,
    goodsList: [],
    pageindex: 1,
    pagesize: 0,
    loadmore: true,
    loaddone: false,
    messageList: [],
    socketOpen: false, // WebSocket连接状态
    socketMsgQueue: [], // WebSocket消息队列
    manualStop: false,
    //  下拉刷新
    triggered: true,
    //  历史记录当前页
    pageNo: 1,
    scrollHeight: '300px',
    right: [{
      text: '删除',
    }, {
      text: '删除',
      style: 'color: #fa3e3e',
    }],
    navbar: {},
    mestaboptions: [{
        text: '消息',
        value: 0,
      },
      {
        text: '服务通知',
        value: 1,
      },
      {
        text: '系统消息',
        value: 2,
      }
    ],
    mestabAct: 0,
    fwlist: [],
    tabop: [0, 0, 0],
    fwpage:1,
    xtpage:1,
    fwpageCount:0,
    xtpageCount:0,
    loadmore_fw:false,
    loadmore_xt:false
  },

  /**
   * 获取code
   */
  getLoginCode() {
    return new Promise((resolve) => {
      promisify(wx.checkSession)().then(() => {
        resolve(resCode);
      }).catch(() => {
        promisify(wx.login)().then((res) => {
          resolve(res.code);
        });
      });
    });
  },

  handleVip(){
    console.log('handleVip=============')
    const {
      userId
    } = this.data;
    this.getLoginCode().then((res) => {
      http.post(api.default, {
        data: {
          action: 'pay_data',
          type:'vip',
          id: 1,
          code: res,
          userid: userId
        }
      }).then((res) => {
        const {
          data
        } = res.data;
        if (res.data.code == 0) {
          const {
            sumPrice,
            source,
            orderId
          } = this.data;
          let result = -1;

          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success(e) {
              result = 1;
            },
            fail(e) {
              result = 0;
            },
            complete() {
              let pages = null;

              //如果来自我的订单或订单详情 && 付款成功
              if (source > 0 && result == 1) {
                pages = getCurrentPages()[getCurrentPages().length - 2];
              }
              wx.redirectTo({
                url: `${getPage.paymentFeedback}?result=${result}&sumTotal=${data.orderAmount}&source=${source}&orderSn=${data.ordersn}`,
                success() {
                  if (pages != undefined || pages != null) {
                    console.log(orderId);
                    pages.paymentUpdate(orderId);
                  }
                }
              });
            }
          });
        } else {
          $toast(res.data.errmsg);
        }
      })
    });
  },

  handleChangeTab(e) {
    console.log('eeeeeeee', e)
    let { tabop } = this.data;
    let {
      act
    } = e.currentTarget.dataset;
    this.setData({
      mestabAct: act
    })
    tabop[act] = 0
    if (act == 1) {
      this.handleGetsysalert((res)=>{
        this.setData({
          fwlist: res.list.reverse(),
          loadmore_fw: false,
        });
      })
    }else if(act==2){
      this.handleGetsysalert((res)=>{
        this.setData({
          xtlist: res.list.reverse(),
          loadmore_xt: false,
        });
      })
    }else if(act == 0){
      this.getMsgList()
    }
    this.setData({
      tabop
    })
  },
  /**
   * 开启
   */
  onOpen(e) {
    // console.log('eeeeeeeee=',e)
    // this.toggleSwipe(e, true);
  },
  toggleSwipe(e, t) {
    const data = e.currentTarget.dataset || e.target.dataset;
    // data(messageId index)
    const {
      messageList
    } = this.data;

    if (data.messageId !== undefined) {
      messageList[data.index].isOpen = t;
      this.setData({
        messageList
      });
    }
  },
  /**
   * 删除事件
   */
  handleDelete(e) {
    const that = this;
    const data = e.currentTarget.dataset || e.target.dataset;
    // data(messageId index)
    console.log('data=====', data)
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '是否删除？',
      success(res) {
        if (res.confirm) {
          const messageList = that.data.messageList;
          http.post(api.default, {
            data: {
              action: 'delfriends',
              fid: data.messageId,
              userid: that.data.userId,
            }
          }).then((res) => {
            messageList.forEach((item, index) => {
              if (item.Fid == data.messageId) {
                messageList.splice(index, 1);
              }
            });
            $toast(`删除成功`, {
              icon: 'success'
            });
            that.setData({
              messageList: messageList
            })
          })
        }
      },
    })
  },

  handleNotouch() {
    return false
  },

  /**
   * 禁止手动滑动
   */
  noSwiping() {
    return false;
  },




  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },

  //连接WebSocket服务器

  connectWebSocket: function () {
    var that = this
    wx.connectSocket({
      url: ChatConfig.CIM_URI,
      success: function (res) {
        console.log('WebSocket连接成功')
      },
      fail: function (res) {
        console.log('WebSocket连接失败:', res)
      }
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开')
      that.setData({
        socketOpen: true
      })
      for (var i = 0; i < that.data.socketMsgQueue.length; i++) {
        that.sendSocketMessage(that.data.socketMsgQueue[i])
      }
      that.setData({
        socketMsgQueue: []
      })
      that.innerOnConnectFinished();
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败:', res)
    })
    wx.onSocketClose(function (res) {
      console.log('WebSocket连接已关闭:', res)
      that.setData({
        socketOpen: false
      });
      // that.innerOnConnectionClosed(res);
    })
    wx.onSocketMessage(function (res) {
      console.log('接收到服务器发送的数据:', res.data)
      that.innerOnMessageReceived(res);
      // var messages = that.data.messages
      // messages.push(res.data)
      // that.setData({
      //   messages: messages,
      //   scrollIntoView: 'message-' + messages.length
      // })
    })
  },
  innerOnConnectFinished: function () {
    let account = "";
    if (account === '' || account === undefined) {
      this.onConnectFinished();
    } else {
      this.bindAccount(account);
    }
  },
  onConnectFinished: function () {
    //获取当前登录用户
    app.getLogin().then((res) => {
      console.log(res);
      this.bind(res.data.user.user_id);
    })
  },
  bind: function (account) {
    storage.set('account', account);
    let deviceId = ""; //storage.get('deviceId');
    if (deviceId === '' || deviceId === undefined) {
      deviceId = this.generateUUID();
      storage.set('deviceId', deviceId)
    }
    let browser = "微信小程序";
    let body = {};
    body.key = ChatConfig.KEY_CLIENT_BIND;
    body.timestamp = new Date().getTime();
    body.data = {};
    body.data.uid = account;
    body.data.channel = ChatConfig.APP_CHANNEL;
    body.data.appVersion = ChatConfig.APP_VERSION;
    body.data.packageName = ChatConfig.APP_PACKAGE;
    body.data.deviceId = deviceId;
    body.data.deviceName = browser;
    console.log(body);
    this.sendRequest(body);
  },
  sendRequest: function (body) {
    let data = {};
    data.type = ChatConfig.SENT_BODY;
    data.content = JSON.stringify(body);
    this.sendSocketMessage(JSON.stringify(data));
  },
  innerOnMessageReceived(e) {
    console.log(e)
    let data = JSON.parse(e.data);
    let type = data.type;
    let body = data.content;
    if (type === ChatConfig.PING) {
      this.pong();
      return;
    }

    if (type === ChatConfig.MESSAGE) {
      let message = JSON.parse(body);
      this.onInterceptMessageReceived(message);
      return;
    }

    if (type === ChatConfig.REPLY_BODY) {
      let reply = JSON.parse(body);
      /*
       * 判断是否是握手鉴权失败
       * 终止后续自动重连
       */
      if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
        this.setData({
          manualStop: true
        });
      }
      this.onReplyReceived(reply);
    }
  },
  pong: function () {
    let data = {};
    data.type = ChatConfig.PONG;
    data.content = ChatConfig.PONG_BODY;
    this.sendSocketMessage(JSON.stringify(data));
  },
  onInterceptMessageReceived(message) {
    /*
     *被强制下线之后，不再继续连接服务端
     */
    if (message.action === ChatConfig.ACTION_999) {
      this.setData({
        manualStop: true
      });
    }
    /*
     *收到消息后，将消息发送给页面
     */
    this.onMessageReceived(message);
    app.globalData.unReadMsg++;
    this.getTabBar().setData({
      number: app.globalData.unReadMsg
    });
  },
  onReplyReceived(reply) {
    console.log(reply);
    if (reply.key === ChatConfig.KEY_CLIENT_BIND && reply.code === ChatConfig.CODE_OK) {
      console.log('登录成功');
      // hideProcess();

      // $('#LoginDialog').fadeOut();

      // $('#MessageDialog').fadeIn();
      // $('#MessageDialog').addClass("in");
      // $("#current_account").text($('#account').val());

    }

    /**
     * 链接鉴权失败
     */
    if (reply.key === ChatConfig.KEY_HANDSHAKE && reply.code === ChatConfig.CODE_UNAUTHORIZED) {
      //hideProcess();
      console.log("鉴权失败");
    }
  },
  onMessageReceived(message) {
    console.log('----------------', message);
    var msgList = this.data.messageList
    var extra = message.extra ? JSON.parse(message.extra) : {};
    console.log('msgList----nold', msgList)
    let index = msgList.findIndex(item => item.FriendId == message.sender)
    var resList = []
    if (index > -1) {
      let spliceList = msgList.splice(index, 1)
      spliceList.forEach(item => {
        item.unreadcount = item.unreadcount + 1;
        item.Msg = message.content
        item.MessageType = extra.MessageType
        item.shichang = extra.shichang
      })
      resList = [...spliceList, ...msgList]
    } else {
      // 新的用户消息
      var item = {
        "Fid": 0,
        "unreadcount": 1,
        "ShopName": extra.ShopName,
        "ToUserID": message.recevier,
        "FromUserId": message.sender,
        "Msg": message.content,
        "ReadStatus": 0,
        "OpId": 0,
        "MessageType": extra.MessageType,
        "timestamp": message.timestamp,
        "shichang": extra.shichang,
        "CreateTime": "2024-06-26 17:50:51",
        "user_name": extra.user_name,
        "nickname": extra.user_name,
        "head_url": extra.head_url,
        "user_id": message.sender
      }

      if (msgList.length > 0) {
        resList = [item, ...msgList]
      } else {
        resList = [item]
      }
    }
    this.setData({
      messageList: resList
    })
    console.log('messagelist----------', this.data.messageList)
  },
  innerOnConnectionClosed: function (e) {
    var _this = this;
    if (!_this.data.manualStop) {
      let time = Math.floor(Math.random() * (30 - 15 + 1) + 15);
      setTimeout(function () {
        console.log("Socket重新连接")
        _this.connectWebSocket(); //重新连接
      }, time);
    }
  },
  generateUUID() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid.replace(/-/g, '');
  },
  // 发送WebSocket消息
  sendSocketMessage: function (message) {
    if (this.data.socketOpen) {
      wx.sendSocketMessage({
        data: message
      })
    } else {
      this.data.socketMsgQueue.push(message)
    }
  },
  // 获取未读消息
  getunreadmsg() {
    http.post(api.default, {
      data: {
        action: 'getunreadmsgcount',
        userid: this.data.userId
      }
    }, false).then(res => {
      app.globalData.unReadMsg = res.data.data;
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          number: app.globalData.unReadMsg
        });
      }
    })
  },
  /**
   * 消息
   */
  bindChat(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    console.log(data, 'eeeeeeeeeeeeeeeeeeeeeee')
    if (data.index) {
      let parm = {
        touserid: data.index.user_id,
        s_shopid:data.index.ShopId,
        user_name: data.index.ShopName || data.index.nickname || '陌生访客',
        img: data.index.head_url
      }
      wxApi.navigateTo(getPage.chat, parm);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    app.getLogin().then((res) => {
      const {
        user
      } = res.data;
      this.setData({
        userId: user.user_id
      })
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      this.goLogin();
    })
    //获取system信息
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
    });
    //  设置滚动区域的高度
    this.setScrollHeight()
  },

  // 获取tab红点
  handleGetMsgCount() {
    let params = {
      data: {
        action: 'getmsgcount',
        userid: this.data.userId
      }
    }
    http.post(api.default, params, false).then(res => {

      let {
        data
      } = res.data;
      let tabop = [data.msgcount, data.fw_notice, data.sys_notice]
      let unReadMsg = data.msgcount + data.fw_notice + data.sys_notice
      this.setData({
        tabop
      })
      app.globalData.unReadMsg = unReadMsg;
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          number: app.globalData.unReadMsg,
        });
      }
    })
  },

  // 获取服务通知/系统消息
  handleGetsysalert(cb) {
    let {mestabAct} = this.data;
    let params = {
      action: 'getsysalert',
      userid: this.data.userId
    }
    if (mestabAct == 1) {
      params.type = 1;
      params.pageIndex = 1;
    } else if (mestabAct == 2) {
      params.type = 2;
      params.pageIndex = 1;
    }
    http.post(api.default, {
      data: params
    }, false).then(res => {

      let {
        data
      } = res.data;
      this.setData({
        fwpageCount: data.pages,
      });
      console.log('data-----------', data)
      cb && cb(data)
    })
  },

  // 获取消息列表
  getMsgList: async function () {
    let params = {
      data: {
        action: 'getfriends',
        userid: this.data.userId
      }
    }
    const res = await http.post(api.default, params, false)
    var list = res.data.data.list;
    list.forEach(item => {
      if (item.MessageType == 6) {
        item.Msg = JSON.parse(item.Msg) || {}
      }
    })
    let listRes = list.filter(f => f.IsShow).reverse()
    this.setData({
      messageList: listRes
    })
  },

  /**
   * 页面滚动函数--监听页面滚动事件
   */
  onPageScroll(e) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow(options) {
    try {
      const rt = await storage.get('page_xt_chat')
      console.log('res------------------------page_xt_chat========',rt)
      this.setData({
        mestabAct: 2
      })
    } catch (error) {
      this.setData({
        mestabAct: 0
      })
    }
    const res = await app.getLogin()
    const {
      user
    } = res.data;
    this.setData({
      userId: user.user_id
    })
    if (this.data.userId > 0) {
      let {mestabAct} = this.data;
      console.log('mestabAct================',mestabAct)
      this.handleGetMsgCount()
      if(mestabAct == 0){
        this.connectWebSocket();
        console.log('yonghuid', this.data.userId)
        this.getMsgList()
      }else if(mestabAct == 1){
        this.handleGetsysalert((res)=>{
          this.setData({
            fwlist: res.list.reverse(),
            loadmore_fw: false,
          });
        })
      }else if(mestabAct ==2){
        this.handleGetsysalert((res)=>{
          console.log('rrrrrrrrrrrrrrrrr709===',res)
          this.setData({
            xtlist: res.list.reverse(),
            loadmore_xt: false,
          });
        })
      }
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          // 这里的数字对应tabbar对应的索引
          selected: 3,
          number: app.globalData.unReadMsg,
          v_count: app.globalData.v_count
        });
      }
      // this.getunreadmsg()
    }
  },

  // 设置滚动区域的高度
  setScrollHeight: function () {
    const client = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
    console.log('设置滚动区域的高度', client)
    var scrollHeight = client
    this.setData({
      scrollHeight
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('onHide------------')
    wx.closeSocket()
    storage.remove('page_xt_chat')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.closeSocket() // 关闭WebSocket连接
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showLoading({
      title: '加载中...',
    })
    // 下拉的实际操作
    var pageNo = this.data.pageNo + 1
    this.setData({
      pageNo
    })
    if (this.timer) {
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(() => {
      this.setData({
        triggered: false
      })
      this.getMsgList()
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 2000)

  },

  // 服务触底
  onFwFWReachBottom() {
    console.log('服务触底')
    console.log('到底了')
    let {
      fwpage,
      fwpageCount,
      loadmore_fw
    } = this.data;
    //未请求完且未在加载中
    if (fwpageCount > fwpage && !loadmore_fw) {
      console.log('eeeeeeeeeeeeeeeeeeeeeeeeeeeee')
      fwpage++;
      loadmore_fw = false;

      //显示加载效果
      this.setData({
        fwpage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.handleGetsysalert((res) => {
        console.log('底部---------getProductsInfo')
        let {
          fwlist
        } = this.data;
        loadmore_fw = false;
        this.setData({
          loadmore_fw,
          fwlist: fwlist.concat(res.list.reverse()),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },
  // 系统触底
  onXtWReachBottom() {
    console.log('服务触底')
    console.log('到底了')
    let {
      xtpage,
      xtpageCount,
      loadmore_xt
    } = this.data;
    //未请求完且未在加载中
    if (xtpageCount > xtpage && !loadmore_xt) {
      console.log('eeeeeeeeeeeeeeeeeeeeeeeeeeeee')
      xtpage++;
      loadmore_xt = false;

      //显示加载效果
      this.setData({
        xtpage,
        loadmore_xt
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.handleGetsysalert((res) => {
        console.log('底部---------getProductsInfo')
        let {
          xtlist
        } = this.data;
        loadmore_xt = false;
        this.setData({
          loadmore_xt,
          xtlist: xtlist.concat(res.list.reverse()),
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      mestabAct
    } = this.data;
    if (mestabAct == 1) {
      this.onFwFWReachBottom()
    } else if (mestabAct == 2) {
      this.onXtWReachBottom()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (this.data.userId > 0) {
      pageshare += "?pid=" + this.data.userId;
    }
    return {
      title: ``,
      imageUrl: '',
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})